# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lv Shenkai
# @Time    : 2022/1/20 12:18
# @File    : classify_events.py
from dynamic_pricing.user_cluster.cluster_user import user_cluster

root_path = r'//dynamic_pricing/user_cluster'


def load_events():
    """
        读取训练集和测试集数据
    :return:返回所有事件
    """

    # 文件地址
    train_events_path = root_path + r'/xiahang/train.txt'
    test_events_path = root_path + r'/xiahang/test.txt'

    # 事件数组
    events = []

    # 读取训练集
    with open(train_events_path) as f:
        rows = f.readlines()
        for row in rows:
            user, item, t = row.split()[:3]
            user = int(user)
            item = int(item)
            t = int(float(t))
            events.append([user, item, t])
    f.close()

    # 读取测试事件集
    with open(test_events_path) as f:
        rows = f.readlines()
        for row in rows:
            user, item, t = row.split()[:3]
            user = int(user)
            item = int(item)
            t = int(float(t))
            events.append([user, item, t])
    f.close()

    return events


def classify_events(k: int):
    """
        将所有事件按照user类别进行分组
    :param k: 对user进行聚类的聚类数目
    :return: 分组后的事件，list形式
            [[user类别属于0的所有事件],[user类别属于1的所有事件],[]...]
    """
    # 读取所有事件
    events = load_events()

    # 用户属性文件路径
    user_data_path = root_path + r'/2020.csv'

    # 获得用户聚类结果
    user_type_dic = user_cluster(user_data_path, k=k)

    is_events_classify = False

    # 所有事件按照user类别进行分组
    if is_events_classify:
        events_class = [[] for _ in range(k)]
        for event in events:
            user = event[0]
            user_type = int(user_type_dic[user])
            events_class[user_type].append(event)
    # 用户分类，事件不分类
    else:
        events_class = [events]

    return events_class, user_type_dic
